package com.asen.libcommon.http.interceptor

import android.text.TextUtils
import com.asen.libcommon.config.BaseConfig
import com.orhanobut.logger.Logger
import okhttp3.*
import okio.Buffer
import java.io.IOException
import java.net.URLDecoder
import java.nio.charset.Charset

/**
 * @date   : 2021/1/18
 * @author : asenLiang
 * @e-mail : liangAisiSen@163.com
 * @desc   : 日志打印 拦截器 （请求方法 、url 、参数，返回结果）
 */
class LoggerInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {

        val request: Request = chain.request().newBuilder().build()

        var response: Response? = null

        try {

            response = chain.proceed(request)

            if (BaseConfig.isDebug) {

                // 请求方法 、url
                printRequest(request)
                // 打印请求参数
                printParams(request.body())
                // 返回结果打印
                printResponse(response)

            }

        } catch (err: Exception) {
            //此处不抛异常  连接超时会crash 没有找到其他好的方法
            err.printStackTrace()
            Logger.v("连接超时！！")
        }

        return response?:chain.proceed(request)

    }

    /** 请求打印 */
    private fun printRequest(request: Request) {

        var logRequest = "${request.method()} --> ${request.url()}"

        // 如果是 get 请求 获取拼接参数
        val oidBody = request.body()

        if (oidBody is FormBody) {
            for (i in 0 until oidBody.size()) {

                val name = URLDecoder.decode(oidBody.encodedName(i), "utf-8")
                val value = URLDecoder.decode(oidBody.encodedValue(i), "utf-8")
                if (!TextUtils.isEmpty(value)) logRequest += "$name  =  $value\n"

            }
        }

        Logger.v(logRequest)

    }

    /** 请求参数打印 */
    private fun printParams(body: RequestBody?) {
        try {

            val buffer = Buffer()

            body?.writeTo(buffer)

            var charset = Charset.forName("UTF-8")
            val contentType = body?.contentType()

            if (contentType != null) charset = contentType.charset(charset)

            val params: String = buffer.readString(charset)

            Logger.v("请求参数---->:$params")

        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    /** 返回结果打印 */
    private fun printResponse(response: Response) {

        val responseBody = response.body()
        val source = responseBody?.source()

        source?.request(Long.MAX_VALUE)

        val buffer = source?.buffer()
        var charset = Charset.forName("UTF-8")
        val contentType = responseBody?.contentType()
        if (contentType != null) charset = contentType.charset(charset)
        val json = buffer?.clone()?.readString(charset)

        Logger.v("返回结果 >>>> ")
        Logger.v("$json")

    }

}